#include <iostream>
#include <memory>
#include "Sock.hpp"
#include "epoll.hpp"

class Epoll_server
{
    static const int num = 64;

public:
    Epoll_server(uint16_t port)
        : _port(port),
          _Listen_sock_ptr(new Sock),
          _epoll_ptr(new Epoller)
    {
    }

    void Init()
    {
        _Listen_sock_ptr->Socket();
        _Listen_sock_ptr->Bind(_port);
        _Listen_sock_ptr->Listen();
    }

    // 链接管理器
    void Accept()
    {
        std::string client_ip;
        uint16_t port;
        int sock = _Listen_sock_ptr->Accept(&client_ip, &port);
        if (sock < 0)
        {
            std::cout << "accept false" << std::endl;
        }
        // 新连接插入后需要将其read设置到epoll中
        else
        {
            _epoll_ptr->Epoll_ctl(EPOLL_CTL_ADD, sock, EPOLLIN);
        }
    }

    void Rcver(int fd)
    {
        char buffer[1024];
        ssize_t n = read(fd, buffer, sizeof(buffer) - 1); // 展示不能确定读到的数据是完整的，还需要添加协议
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << "get a messge: " << buffer << std::endl;
            // wrirte
            std::string echo_str = "server echo $ ";
            echo_str += buffer;
            write(fd, echo_str.c_str(), echo_str.size());
        }
        else if (n == 0)
        {
            // 注意：易错点
            _epoll_ptr->Epoll_ctl(EPOLL_CTL_DEL, fd, 0);
            close(fd);
        }
        else
        {
            _epoll_ptr->Epoll_ctl(EPOLL_CTL_DEL, fd, 0);
            close(fd);
        }
    }

    void Dispatcher(struct epoll_event revs[], int n)
    {
        for (int i = 0; i < n; i++)
        {
            uint32_t event = revs[i].events;
            int fd = revs->data.fd;
            if (event & EPOLLIN)
            {
                if (fd == _Listen_sock_ptr->Fd()) // 检查是否是有链接就绪
                {
                    Accept();
                }
                else
                {
                    Rcver(fd);
                }
            }
            else if (event & EPOLLOUT)  //检查是否写事件就绪
            {
            }
            else  //其他事件就绪
            {
            }
        }
    }

    void Start()
    {
        struct epoll_event revs[num];
        _epoll_ptr->Epoll_ctl(EPOLL_CTL_ADD, _Listen_sock_ptr->Fd(), EPOLLIN);
        for (;;)
        {
            int n = _epoll_ptr->Epoll_wait(revs, num);
            if (n < 0)
            {
                std::cout << "epoll wait false" << std::endl;
            }
            else if (n == 0)
            {
                std::cout << "time wait......" << std::endl;
            }
            else
            {
                // 有事件就绪
                Dispatcher(revs, n);
            }
        }
    }

    ~Epoll_server()
    {
        _Listen_sock_ptr->Close();
    }

private:
    std::shared_ptr<Sock> _Listen_sock_ptr;
    std::shared_ptr<Epoller> _epoll_ptr;
    uint16_t _port;
};